import Cookie from 'js-cookie'

function toNormalArr(data) {
  return JSON.parse(JSON.stringify(data));
}

function getInt(s) {
  return parseInt(s)
}

function getParams(data, fieldStr) {
  let params = {}
  let fields = fieldStr.split(',')
  for(const index in fields) {
    params[index] = data[index]
  }
  return params
}

function setField(items, field, value) {
  let params = []
  params[field] = value
  return items.map((item)=>{ return Object.assign(item,params)})
}

function removeField(items,field,value) {

}

function getOptionsItems(items,valueField='id',labelField='name') {
  let arr = []
  for(let i = 0;i < items.length;i++) {
    arr.push({'value':items[i][valueField], 'label':items[i][labelField]})
  }
  return arr
}

//设置active
function setItemActive(items, item, fieldName = 'id', className = 'active', trueValue = true, falseValue = false) {
  for(let i = 0;i < items.length; i++) {
    items[i][className] = falseValue
  }
  item[className] = trueValue
}
function numFilter(value) {
  return Number(value).toFixed(2)//截取当前数据到小数点后两位
}
function getLabelFromOptions(options, value) {
  let label = ''
  for(let i = 0;i < options.length; i++) {
    if (options[i].value==value) {
      label = options[i].label
      break;
    }
  }
  return label
}
function animate(obj, css, interval, speedFactor, func) {
	clearInterval(obj.timer);
	function getStyle(obj, prop) {
		if (obj.currentStyle)
			return obj.currentStyle[prop]; // ie
		else
			return document.defaultView.getComputedStyle(obj, null)[prop];  // 非ie
	}
	obj.timer = setInterval(function(){
		var flag = true;
		for (var prop in css) {
			var cur = 0;
			if(prop == "opacity")
				cur = Math.round(parseFloat(getStyle(obj, prop)) * 100);
			else
				cur = parseInt(getStyle(obj, prop));
			var speed = (css[prop] - cur) * speedFactor;
			speed = speed > 0 ? Math.ceil(speed): Math.floor(speed);
			if (cur != css[prop])
				flag = false;
			if (prop == "opacity") {
				obj.style.filter = "alpha(opacity : '+(cur + speed)+' )";
				obj.style.opacity = (cur + speed) / 100;
			}
			else
				obj.style[prop] = cur + speed + "px";
		}
		if (flag) {
			clearInterval(obj.timer);
			if (func)
				func();
		}
	}, interval);
}

function validRequired(rule, value, callback){
  if (value === '') {
    callback(new Error('Please enter your password'));
  } else {
    if (this.formCustom.passwdCheck !== '') {
      // 对第二个密码框单独验证
      this.$refs.formCustom.validateField('passwdCheck');
    }
    callback();
  }
}

function changeItemsKey(items, keys) {
  var data = []
  for (var i = 0; i< items.length; i++) {
    var newItem = {}
    for (var key in keys) {
      if (typeof(items[i][key])!=undefined) {
        newItem[keys[key]] = items[i][key]
      }
    }
    if (items[i].display==1) {
      data.push(newItem)
    }
  }
  return data
}

function timeToDate(timestamp) {
	var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	var D = date.getDate() < 10? '0'+date.getDate() + ' ' : date.getDate() + ' ';
	var h = (date.getHours() < 10? '0'+date.getHours() : date.getHours()) + ':';
	var m = (date.getMinutes() < 10? '0'+date.getMinutes() : date.getMinutes()) + ':';
	var s = (date.getSeconds() < 10? '0'+date.getSeconds() : date.getSeconds());
	return Y+M+D+h+m+s;
}

function isEmptyObject(obj) {
  return JSON.stringify(obj) === '{}' ? true : false
}

function dateFormat(date, fmt){
  if (!date) {
    return ''
  }
  if (typeof(date) == 'number' || typeof(date) == 'string') {
    var date = new Date(date*1000)
  }
  var o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}

function inArray(search,array){
    for(var i in array){
        if(array[i]==search){
            return true;
        }
    }
    return false;
}

function isUserLogin() {
  return Cookie.get('token') ? true : false
}

function getCookieInServer(req, value) {
  let serviceCookie = {};
  req && req.headers.cookie && req.headers.cookie.split(';').forEach(function (val) {
    let parts = val.split('=');
    serviceCookie[parts[0].trim()] = (parts[1] || '').trim();
  });
  if (value in serviceCookie) {
    return serviceCookie[value]
  } else {
    return ''
  }
}

function changeDate(dateA) {
  var dateee = new Date(dateA).toJSON();
  var date = new Date(+new Date(dateee)+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
  return date;
}

let configs =  {
  toNormalArr: toNormalArr,
  getInt: getInt,
  animate: animate,
  getParams: getParams,
  setField: setField,
  setItemActive: setItemActive,
  numFilter: numFilter,
  getOptionsItems: getOptionsItems,
  changeItemsKey: changeItemsKey,
  timeToDate: timeToDate,
  getLabelFromOptions: getLabelFromOptions,
  inArray: inArray,
  isEmptyObject: isEmptyObject,
  timeToDate: timeToDate,
  dateFormat: dateFormat,
  isUserLogin: isUserLogin,
  changeDate: changeDate,
  getCookieInServer: getCookieInServer
}

export default configs
